#pragma once

#include<iostream>
#include<queue>
#include<pthread.h>
#include<semaphore.h>
#include<vector>

const int gcap = 5;

template <class T>
class RingQueue
{

private:
    void P(sem_t &s)
    {
        sem_wait(&s);
    }
    void V(sem_t &s)
    {
        sem_post(&s);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }


public:
    RingQueue(const int cap = gcap)
    :_cap(cap),
    _ring(cap),
    _c_step(0),
    _p_step(0)
    {
        pthread_mutex_init(&_c_mutex,nullptr);
        pthread_mutex_init(&_p_mutex,nullptr);

        sem_init(&_data_sem,0,0);
        sem_init(&_space_sem,0,cap);

    }

    //生产
    void push(const T &in)
    {
        P(_space_sem);//申请空闲空间
        Lock(_p_mutex);//对操作加锁
        _ring[_p_step++] = in;//往循环队列数组里增加数据
        _p_step %= _cap;//进行循环
        Unlock(_p_mutex);//对操作解锁
        V(_data_sem);//增加数据产品的数量
 
    }

    //消费呢
    void pop(T *out)
    {
        P(_data_sem);
        Lock(_c_mutex);
        *out = _ring[_c_step++];
        _c_step %= _cap;
        Unlock(_c_mutex);
        V(_space_sem);
      
    }

    ~RingQueue()
    {
        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);

        sem_destroy(&_data_sem);
        sem_destroy(&_space_sem);

    }


private:
    std::vector<T> _ring;
    int _cap;
    sem_t _data_sem;//数据的信号量锁
    sem_t _space_sem;//空间的信号量锁
    int _c_step;//消费者的位置
    int _p_step;//生产者的位置

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;
};


